package com.example.securitydemo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Package: com.example.securitydemo.config
 * @ClassName: MySecurityConfig
 * @Author: Think
 * @CreateTime: 2021/7/27 11:24
 * @Description:
 */
/*@EnableWebSecurity*/
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 对请求进行鉴权的配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 任何角色允许访问
                .antMatchers("/", "/index").permitAll()
                // 仅admin角色可以访问
                .antMatchers("/admin/**").hasRole("admin")
                // admin和manager两个角色可以访问
                .antMatchers("/manager/**").hasAnyRole("admin", "manager");

        // 没有权限进入内置的登录页面
        http.formLogin();
        // 自定义登出逻辑
        http.logout().logoutUrl("/myLogOut").logoutSuccessUrl("/index");
        // 暂时关闭CSRF校验，允许get请求登出
        http.csrf().disable();
        // 开启remember me功能
        http.rememberMe();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        // 指定使用BCryptPasswordEncoder对前端传过来的明文密码进行encode
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                // 用户的真实密码需要encode，security是比较两个密文是否一致
                .withUser("root").password(encoder.encode("root123")).roles("admin", "manager")
                .and()
                .withUser("zhang").password(encoder.encode("mm000")).roles("manager");
    }

}
